package com.fj.netty.rpc.client;

import com.fj.netty.rpc.client.handler.RpcResponseMessageHandler;
import com.fj.netty.rpc.message.RpcRequestMessage;
import com.fj.netty.rpc.protocol.RpcMessageCodec;
import com.fj.netty.rpc.protocol.RpcMessageLengthFieldDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author fj
 * @date 2024/1/17 17:16
 */
public class RpcClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Channel channel = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new RpcMessageLengthFieldDecoder());
                            ch.pipeline().addLast(new RpcMessageCodec());
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    RpcRequestMessage message = new RpcRequestMessage();
                                    message.setInterfaceName("com.fj.netty.rpc.api.HelloService");
                                    message.setMethodName("sayHello");
                                    message.setReturnType(String.class);
                                    message.setParamTypes(new Class[]{String.class});
                                    message.setParamObjects(new Object[]{"ZhangSan"});
                                    ctx.writeAndFlush(message);
//                                    super.channelActive(ctx);
                                }
                            });
                            ch.pipeline().addLast(new RpcResponseMessageHandler());
                        }
                    }).connect("127.0.0.1", 6789).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
